package com.cpi.cornpp.futuresversions.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.futuresversions.exception.CornFuturesVersionsException;
import com.cpi.cornpp.futuresversions.form.CornFuturesVersionsForm;
import com.cpi.cornpp.futuresversions.services.CornFuturesVersionsService;
import com.cs.common.utils.NumberUtil;

/**
 * Corn Futures Versions Go Add Action
 * @author Edgar Joao
 *
 */
public class CornFuturesVersionsGoAddAction extends Action{
	/** Identifier default workflow*/
	private final static String DEFAULT = "default";//$NON-NLS-1$
	/** Custom exception */
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$	
	private static final String VERSION_ID = "versionId";//$NON-NLS-1$
	
	/**
	 * Metodo execute
	 * @author Edgar Joao
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws CornFuturesVersionsException {
		
		HttpSession httpSession = null;		
		CornFuturesVersionsService cornFuturesVersionsService = null;
		List cornListFuturesVersions = null;
		CornFuturesVersionsForm cornFuturesVersionsForm = null;
		cornFuturesVersionsForm = (CornFuturesVersionsForm) form;
		int versionId = 0;
		try{
			httpSession = request.getSession();
			cornFuturesVersionsService = new CornFuturesVersionsService();
			cornListFuturesVersions = new ArrayList(0);
			versionId = NumberUtil.getInt(httpSession.getAttribute(VERSION_ID));
			cornListFuturesVersions = cornFuturesVersionsService.listCornFuturesPeriodsVersion(versionId);
			
			request.setAttribute("cornListFuturesVersions", cornListFuturesVersions);
			
		}catch (CornFuturesVersionsException cornFuturesVersionsException){
			httpSession.setAttribute(CUSTOM_EXCEPTION, cornFuturesVersionsException);
			throw cornFuturesVersionsException;
		}
		catch (Exception e){
			CornFuturesVersionsException costElementException=null;
			e.printStackTrace(System.out);
			costElementException= new CornFuturesVersionsException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			httpSession.setAttribute(CUSTOM_EXCEPTION, costElementException);
			throw costElementException;
		} 
		cornFuturesVersionsForm.reset(mapping, request);
		return mapping.findForward(DEFAULT);
	}
}
